﻿using AutoUpdater;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UcAutoUpdate
{
    public partial class FrmCheck : Form
    {
        private string mainPath = "main"; //主程序目录
        private string ServerUrl;
        private string callBackExeName;
        private string title;
        private string processName;
        private bool startAppAfterClose = false; //关闭升级窗体前，是否启动应用程序。
        private string currentVersion;
        private string startDirectoryPath;

        private CsUpdateSelf updater;   

        public FrmCheck()
        {
            InitializeComponent();

            ServerUrl = ConfigurationManager.AppSettings["ServerUrl"];
            callBackExeName = ConfigurationManager.AppSettings["CallbackExeName"];
            title = ConfigurationManager.AppSettings["Title"];
            processName = callBackExeName.Substring(0, callBackExeName.Length - 4);
            startDirectoryPath = System.Windows.Forms.Application.StartupPath;

            this.FormClosing += FrmCheck_FormClosing;
        }

        private void FrmCheck_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(updater!=null)
            {
                updater.Start();
            }
        }

        private void FrmCheck_Shown(object sender, EventArgs e)
        {
            updater = new CsUpdateSelf();

            updater.UpdateCompleted += Updater_UpdateCompleted;
            updater.Start();
        }

        private void Updater_UpdateCompleted(bool arg1, bool arg2)
        {
            if (arg1)
            {
                string processName = this.callBackExeName.Substring(0, this.callBackExeName.Length - 4);
                ESBasic.Helpers.ApplicationHelper.ReleaseAppInstance(processName);

                if (!this.startAppAfterClose)
                {
                    Application.Exit();
                    return;
                }

                if (arg2)
                {
                    string filename = Path.Combine(System.Windows.Forms.Application.StartupPath, "tempUpdate","update.exe");
                    if (File.Exists(filename))
                    {
                        System.Diagnostics.Process myProcess = System.Diagnostics.Process.Start(filename);
                    }
                }
                else
                {
                    string sourcePath = Path.Combine(System.Windows.Forms.Application.StartupPath);
                    if(CopyDirectory(sourcePath, System.Windows.Forms.Application.StartupPath,true))
                    {
                        string filename = Path.Combine(startDirectoryPath, this.callBackExeName);
                        if (File.Exists(filename))
                        {
                            System.Diagnostics.Process myProcess = System.Diagnostics.Process.Start(filename);
                        }
                    }
                }
                Application.Exit();
            }
            else
            {

            }
        }

        /// <summary>
        /// 文件夹下所有内容copy
        /// </summary>
        /// <param name="SourcePath">要Copy的文件夹</param>
        /// <param name="DestinationPath">要复制到哪个地方</param>
        /// <param name="overwriteexisting">是否覆盖</param>
        /// <returns></returns>
        private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
        {
            bool ret = false;
            try
            {
                SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
                DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";

                if (Directory.Exists(SourcePath))
                {
                    if (Directory.Exists(DestinationPath) == false)
                        Directory.CreateDirectory(DestinationPath);

                    foreach (string fls in Directory.GetFiles(SourcePath))
                    {
                        FileInfo flinfo = new FileInfo(fls);
                        flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
                    }
                    foreach (string drs in Directory.GetDirectories(SourcePath))
                    {
                        DirectoryInfo drinfo = new DirectoryInfo(drs);
                        if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)
                            ret = false;
                    }
                }
                ret = true;
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return ret;
        }
    }
}
